<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-form-item prop="username">
          <el-input v-model="filters.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="telephone">
          <el-input v-model="filters.telephone" placeholder="手机号码"></el-input>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="filters.status" style="width:100%">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常使用" value="0"></el-option>
            <el-option label="已注销" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <kt-button :label="$t('action.reset')" type="primary" @click="resetForm('filters')"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <kt-button type="active" @click="handleEditPassword" label="重置密码">

            </kt-button>
          </el-form-item>
          <el-form-item>
            <kt-button type="active" @click="disableUser" label="禁用/解禁"></kt-button>
          </el-form-item>
          <el-form-item>
            <ele-import
              :fields="fields"
              :filepath="filepath"
              :requestFn="requestFn"
              :rules="rules"
              :tips="tips"
              :title="title"
              :visible.sync="visible"
              @close="handleCloseImport"
              @finish="handleFinishImport"
            />
            <el-button
              @click="handleOpen"
              type="active"
            >会员导入
            </el-button>
          </el-form-item>
          <el-form-item>
            <kt-button type="active" label="会员模板下载">
              <el-link
                :href="filepath"
                target="_blank"
              >会员模板下载
              </el-link>
            </kt-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o" @click="downloadExcel"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog
        ref="tableColumnFilterDialog"
        :columns="columns"
        @handleFilterColumns="handleFilterColumns"
      ></table-column-filter-dialog>
    </div>
    <!--表格内容栏-->
    <cy-table
      :height="350"
      :data="pageResult"
      :columns="filterColumns"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      @selectionChange="selectionChange"
      ref="CyTable"
    ></cy-table>
    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      width="40%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="80px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="会员名称" prop="username">
          <el-input v-model="dataForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="dataForm.password" auto-complete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="telephone">
          <el-input v-model="dataForm.telephone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="dataForm.nickname" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="会员等级" prop="grade_id">
          <el-select v-model="dataForm.grade_id" placeholder="请选择" style="width:100%">
            <el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
        >{{$t('action.submit')}}
        </el-button>
      </div>
    </el-dialog>
    <!--重置密码-->
    <el-dialog
      title="重置密码"
      width="40%"
      :visible.sync="editDialogPassword"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataFormPassword"
        label-width="80px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataFormPassword.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="会员名称" prop="username">
          <el-input v-model="dataFormPassword.username" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="dataFormPassword.password" auto-complete="off" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogPassword = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitFormPassword"
          :loading="editLoading"
        >{{$t('action.submit')}}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import CyTable from "@/views/Core/CyTable";
  import KtButton from "@/views/Core/KtButton";
  import {format} from "@/utils/datetime";
  import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
  import EleImport from 'vue-ele-import';
  import {validatePhone,validatePsdReg } from "@/utils/validate";
  export default {
    components: {
      CyTable,
      KtButton,
      TableColumnFilterDialog,
      EleImport
    },
    data() {
      return {
        size: "small",
        gradeList: [],
        filters: {
          key: "",
          type: "",
          t: "member",
          queryname: ""
        },
        columns: [
          {prop: "id", label: "序号", minWidth: 50},
          {prop: "username", label: "用户名", minWidth: 100},
          {prop: "telephone", label: "手机号码", minWidth: 100},
          {prop: "company", label: "所属公司", minWidth: 80},
          {prop: "nickname", label: "昵称", minWidth: 80},
          {prop: "register_type", label: "注册类型", minWidth: 80},
          {prop: "register_time", label: "注册时间", minWidth: 120},
          {prop: "remainder", label: "会员余额", minWidth: 80},
          {prop: "gradename", label: "会员等级", minWidth: 80},
          {prop: "integration", label: "会员积分", minWidth: 80},
          {prop: "status_alias", label: "状态", minWidth: 120}
        ],
        filterColumns: [],
        pageRequest: {pageNum: 1, pageSize: 10},
        pageResult: {},

        operation: false, // true:新增, false:编辑
        editDialogVisible: false, // 新增编辑界面是否显示
        editDialogPassword: false,//修改密码界面是否显示
        editLoading: false,
        dataFormRules: {
          username: [{required: true, message: "请输入会员名称", trigger: "blur"},
                    { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }],
          password: [{required: true, validator: validatePsdReg , trigger: "blur"}],
          telephone: [{required: true, validator: validatePhone, trigger: "blur"}],
          nickname: [{required: true, message: "请输入昵称", trigger: "blur"},
                    { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }]
        },
        // 新增编辑界面数据
        dataForm: {
          id: "",
          username: "",
          password: "",
          telephone: "",
          nickname: "",
          grade_id: ""
        },
        //修改密码
        dataFormPassword: {
          id: "",
          username: "",
          password: ""
        },
        checked: [],
        title: '会员导入',
        tips: ['用户名必填', '手机号码必填', '密码必填', '昵称必填', '会员等级必填'],
        fields: {
          username: '用户名',
          telephone: '手机号码',
          password: '密码',
          nickname: '昵称',
          sex: '性别',
          birth_date: '出生日期',
          company: '所属单位',
          grade_id: '会员等级（联盟会员，PLUS会员，普通会员）'
        },
        rules: {
          telephone: [{type: 'number', message: '手机号必须为数字'},
            {required: true, message: "用户名必填"}],
          password: [{required: true, message: "密码必填"}],
          nickname: [{required: true, message: "昵称必填"}],
          grade_id: [{required: true, message: "会员等级必填"}],
        },
        filepath: '/static/excels/memberdemo.xls', //会员模板下载地址
        visible: false,
      };
    },
    methods: {
      // 获取分页数据
      findPage: function (data) {
        this.$refs.CyTable.findPage(this.filters);
      },
      //初始化页面数据
      init() {
        let that = this;
        this.utils.request.queryUserList({t: "memberGrade"}, function (data) {
          that.gradeList = data.data;
        });
      },
      //选择框
      selectionChange: function (params) {
        this.checked = params.selections
      },
      // 批量删除
      handleDelete: function (data) {
        if (data != null && data.params != null && data.params.length > 0) {
          let ids = data.params.map(item => item.id).toString();

          let params = {};
          params.t = "member";
          params.ids = ids;
          let this_ = this;
          this.utils.request.deleteUserInfo(params, function (res) {
            if (res.code == "0000") {
              this_.$message({message: "操作成功", type: "success"});
              this_.findPage(null);
            } else {
              this_.$message({message: "操作失败, " + res.msg, type: "error"});
            }
          });
        }
      },
      // 显示新增界面
      handleAdd: function () {
        this.editDialogVisible = true;
        this.operation = true;
        this.dataFormRules.password[0].required = true;
        this.resetForm("dataForm");
      },
      // 显示编辑界面
      handleEdit: function (params) {
        this.editDialogVisible = true;
        this.operation = false;
        this.$nextTick(function () {
          this.dataFormRules.password[0].required = false;
          params.row.password = "";
          params.row.status = params.row.status + "";
          this.dataForm = Object.assign({}, params.row);
        });
      },
      // 显示修改密码界面
      handleEditPassword: function () {
        if (this.checked.length == 1) {
          this.dataFormRules.username[0].required = false;
          this.editDialogPassword = true;
          this.dataFormPassword.username = this.checked[0].username;
          this.dataFormPassword.id = this.checked[0].id;
        } else {
          this.$message({message: '请选择一条需要操作的记录！', type: 'error'})
        }
      },
      // 编辑
      submitForm: function () {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {}).then(() => {
              let params = Object.assign({}, this.dataForm);
              if (params.id.length === 0) {
                params.register_type = "后台注册";
              }
              params.t = "member";
              let this_ = this;
              this.utils.request.editInfo(params, function (res) {
                if (res.code == "0000") {
                  this_.$message({message: "操作成功", type: "success"});

                  this_.$refs["dataForm"].resetFields();

                  this_.editDialogVisible = false;

                  this_.findPage(null);
                } else {
                  this_.$message({message: "操作失败, " + res.msg, type: "error"});
                }
              });
            });
          }
        });
      },
      // 编辑
      submitFormPassword: function () {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {}).then(() => {
              let params = Object.assign({}, this.dataFormPassword);
              params.t = "member";
              let this_ = this;
              this.utils.request.editInfo(params, function (res) {
                if (res.code == "0000") {
                  this_.$message({message: "操作成功", type: "success"});

                  this_.dataFormRules.username[0].required = true;
                  this_.dataFormPassword.username = "";
                  this_.dataFormPassword.id = "";
                  this_.dataFormPassword.password = "";
                  this_.editDialogPassword = false;

                  this_.findPage(null);
                } else {
                  this_.$message({message: "操作失败, " + res.msg, type: "error"});
                }
              });
            });
          }
        });
      },
      // 修改用户状态
      disableUser: function () {
        if (this.checked.length == 1) {
          this.$confirm("确认修改吗？", "提示", {}).then(() => {
            let params = {};
            params.t = "member";
            params.id = this.checked[0].id;
            let this_ = this;
            this.utils.request.disableUser(params, function (res) {
              if (res.code == "0000") {
                this_.$message({message: "操作成功", type: "success"});

                this_.findPage(null);
              } else {
                this_.$message({message: "操作失败, " + res.msg, type: "error"});
              }
            });
          });
        } else {
          this.$message({message: '请选择一条需要操作的记录！', type: 'error'})
        }
      },
      // 时间格式化
      dateFormat: function (row, column, cellValue, index) {
        return format(row[column.property]);
      },

      resetForm(formName) {
        if (this.$refs[formName] != undefined) {
          this.$refs[formName].resetFields();
          this.findPage(null);
        }
      },

      // 处理表格列过滤显示
      displayFilterColumnsDialog: function () {
        this.$refs.tableColumnFilterDialog.setDialogVisible(true);
      },
      // 处理表格列过滤显示
      handleFilterColumns: function (data) {
        this.filterColumns = data.filterColumns;
        this.$refs.tableColumnFilterDialog.setDialogVisible(false);
      },
      // 处理表格列过滤显示
      initColumns: function () {
        let temp = [];

        $.each(this.columns, function (key, val) {
          temp.push(val);
        });
        this.filterColumns = temp;
      },
      //列表下载
      downloadExcel() {
        this.$confirm("确定下载列表文件?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let filename = "会员维护下载";
            this.$refs.CyTable.exportData(
              this.filters,
              this.filterColumns,
              filename
            );
          })
          .catch(() => {
          });
      },
      beforeUpload(file) {
        const isLt1M = file.size / 1024 / 1024 < 1
        if (isLt1M) {
          var formdata = new FormData();
          formdata.append('upfile', file);
          this.$axios.post(this.utils.host + '/member/ajaxUploadMemberExcel?token=' + localStorage.getItem('token'), formdata, {headers: {'Content-type': 'multipart/form-data'}});
          return true
        }
        this.$message({message: '导入excel出错！', type: 'warning'})
        return false
      },
      async requestFn(data) {
        let params = {};
        params.data = JSON.stringify(data);
        /* return Promise.reject({ 1: { age: '名字错了' } })*/
        return Promise.resolve()
      },
      handleCloseImport() {
      },
      handleFinishImport() {
      },
      handleOpen() {
        this.visible = true
      }
    },
    mounted() {
      this.initColumns();
      this.init();
    }
  };
</script>

<style scoped>
</style>
